package com.sxkj.common.zookeeper.test;

import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class RedisRunnable implements Runnable {

    /** 处理main线程阻塞（等待所有子线程） */
    private CountDownLatch countDown;

    /** 线程名字 */
    private String  threadName;
    private RedissonClient redissonClient;


    public RedisRunnable(CountDownLatch countDownLatch, String threadName
    ,RedissonClient redissonClient) {
        this.countDown = countDownLatch;
        this.redissonClient = redissonClient;
        this.threadName = threadName;
    }

    @Override
    public void run() {
//        System.out.println( "[" + threadName + "] Running ! [countDownLatch.getCount() = " + countDown.getCount() + "]." );

//        RedissonAutoConfiguration RedissonAutoConfiguration = new RedissonAutoConfiguration();
//        RedissonClient redissonClient = RedissonAutoConfiguration.getRedisson();
//        String resourceName = "REDLOCK_KEY";
        RedissonRedLock redLock;
        try {
            RLock lock = redissonClient.getLock("REDLOCK_KEY");
            // 向1个redis实例尝试加锁
            redLock = new RedissonRedLock(lock);
            // isLock = redLock.tryLock();
            // 500ms拿不到锁, 就认为获取锁失败。10000ms即10s是锁失效时间。
            boolean isLock = redLock.tryLock(500, 10000, TimeUnit.MILLISECONDS);
            if (isLock) {
                //TODO 获取到锁，处理相关业务
                System.out.println(" 获取到锁，处理相关业务");
                Thread.sleep(50);  //就按照每个业务处理平均200ms完成
//                System.out.println( "获取锁结果："+isLock);
                //TODO if get lock success, do something;
            }else{
                System.out.println("已上锁了....");
            }
            redLock.unlock();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            // 无论如何, 最后都要解锁
//            redLock.unlock();
            countDown.countDown();
//            redissonClient.shutdown();
        }
    }

}
